import http from '@/utils/http'

const BASE_URL = 'template/testTemplate'

// 模板信息接口
export interface TestTemplate {
  id: number
  name: string
  version?: number
  filePath: string
  remark?: string
  createTime?: string
  createUser?: number
  updateTime?: string
  updateUser?: number
}

export interface Result<T = any> {
    code: string | number
    message?: string  // 后端 Result 类使用的字段名
    data: T
    success: boolean
    timestamp: number
  }

// 查询条件
export interface TestTemplateQuery {
  page?: number
  size?: number
  name?: string
  version?: number
}

export interface TemplatePlaceholderKV {
  key: string
  value: string
}

/** 分页查询测试模板 */
export function pageTestTemplates(query: TestTemplateQuery) {
  return http.get<Result<{ list: TestTemplate[]; total: number }>>(`${BASE_URL}/page`, query)
}

/** 删除测试模板 */
export function deleteTestTemplate(id: number) {
  return http.del(`${BASE_URL}/${id}`)
}

/** 批量删除测试模板 */
export function deleteTestTemplates(ids: number[]) {
  return http.del(`${BASE_URL}/batch`, ids)
}

/** 下载测试模板 */
export function downloadTestTemplate(id: number) {
  return http.download(`${BASE_URL}/${id}/download`)
}

/** 上传测试模板 */
export function uploadTestTemplate(file: File, name: string, version?: number, remark?: string) {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('name', name)
  if (version !== undefined) {
    formData.append('version', version.toString())
  }
  if (remark !== undefined && remark !== null && remark.trim() !== '') {
    formData.append('remark', remark)
  }
  return http.post<Result<TestTemplate>>(`${BASE_URL}/upload`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/** 查询模板占位符 */
export function listTemplatePlaceholders() {
  return http.get<Result<TemplatePlaceholderKV[]>>(`${BASE_URL}/placeholders`)
}

/** 导出模板占位符 */
export function exportTemplatePlaceholders() {
  return http.download(`${BASE_URL}/placeholders/export`)
}

